package com.epfresh.supplier.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.BaseFragment;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.tablayout.CommonTabLayout;
import com.epfresh.api.widget.tablayout.TabEntity;
import com.epfresh.api.widget.tablayout.listener.OnTabSelectListener;
import com.epfresh.supplier.R;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.entity.StoreInfo;
import com.epfresh.supplier.fragment.SoldFragment;

import java.util.ArrayList;

public class ProductActivity extends BaseActivity implements OnTabSelectListener {

    private CommonTabLayout lyTab;
    private ViewPager vp;
    private FragmentManager fragmentManager;
    private SoldFragment soldUpFragment;
    private SoldFragment soldDraftFragment;
    private SoldFragment soldAuditFragment;
    private SoldFragment soldDownFragment;
    private BaseFragment currentFragment;
    private int currentFragmentIndex;
    private ImageView img_now_add_product,img_pre_add_product;
    private TextView txt_now_add_product,txt_pre_add_product;


    private View vCashSales;
    private View vPreSales;

    boolean isDc;
    int pageCount = 4;

    int productType;

//    (0, "草稿"),
//    (1, "已上架"),
//    (2, "未上架"),
//    (4, "审核中")

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product);
        fragmentManager = getSupportFragmentManager();

        toolbarTitle.setText(R.string.post_product);
        ivBack.setVisibility(View.VISIBLE);
        righticon.setVisibility(View.VISIBLE);
        righticon.setImageResource(R.mipmap.search);
        righticon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ProductActivity.this,SpotGoodsSearchActivity.class);
                startActivity(intent);
            }
        });
        rightbtn.setVisibility(View.GONE);
        rightbtn.setText("搜索");
        rightbtn.setTextColor(0xff6f6f6f);
        rightbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO: 2018/12/25
                Intent intent = new Intent(ProductActivity.this,SpotGoodsSearchActivity.class);
                startActivity(intent);
            }
        });
        rightbtn2.setVisibility(View.GONE);
        rightbtn2.setText("分类");
        rightbtn2.setTextColor(0xff6f6f6f);
        rightbtn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intoProductClassify();
            }
        });
        initData(savedInstanceState);
        //根据tag寻找fragment
        initFragment();
        //初始化view
        initView();
        //加载数据


    }

    private void intoProductClassify() {
        Intent intent = new Intent(this,ProductClassifyManagerActivity.class);

        startActivity(intent);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        String status = intent.getStringExtra("status");

        setIntent(intent);

        if("1".equals(status)){
            vp.setCurrentItem(0);
            lyTab.setCurrentTab(0);
        } else if ("0".equals(status)){
            vp.setCurrentItem(1);
            lyTab.setCurrentTab(1);
        }else if ("2".equals(status)){
            vp.setCurrentItem(2);
            lyTab.setCurrentTab(2);
        }

        refreshList();

    }

    private void initData(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            currentFragmentIndex = savedInstanceState.getInt(Constant.KEY_HOME_STATE_INDEX);
            getIntent().putExtra("productType", savedInstanceState.getInt("productType"));
        }

        productType = getIntent().getIntExtra("productType", 2);



//        selectPage(currentFragmentIndex);
    }


    private void initView() {

        vp = (ViewPager) findViewById(R.id.vp);
        lyTab = (CommonTabLayout) findViewById(R.id.ly_navigation);
        vCashSales = findViewById(R.id.rl_cash_sales);
        img_now_add_product = findViewById(R.id.img_now_add_product);
        img_pre_add_product = findViewById(R.id.img_pre_add_product);
        txt_now_add_product = findViewById(R.id.txt_now_add_product);
        txt_pre_add_product = findViewById(R.id.txt_pre_add_product);
        vPreSales = findViewById(R.id.rl_pre_sales);

        vCashSales.setOnClickListener(this);
        vPreSales.setOnClickListener(this);
        if (productType == 1) {//现货
            pageCount = 3;
            vCashSales.setVisibility(View.VISIBLE);
            vPreSales.setVisibility(View.GONE);
            if (BaseApplication.getInstance().getMerchant().isAuthNeedBind()) {
                img_now_add_product.setImageResource(R.mipmap.product_add_grey);
                txt_now_add_product.setTextColor(Color.parseColor("#aaaaaa"));
            }else {
                img_now_add_product.setImageResource(R.mipmap.product_add);
                txt_now_add_product.setTextColor(Color.parseColor("#f13d1a"));
            }
        } else if (productType == 2) {//预售
            pageCount = 4;
            righticon.setVisibility(View.GONE);
            vCashSales.setVisibility(View.GONE);
            vPreSales.setVisibility(View.VISIBLE);
            if (BaseApplication.getInstance().getMerchant().isAuthNeedBind()) {
                img_pre_add_product.setImageResource(R.mipmap.product_add_grey);
                txt_pre_add_product.setTextColor(Color.parseColor("#aaaaaa"));
            }else {
                img_pre_add_product.setImageResource(R.mipmap.product_add);
                txt_pre_add_product.setTextColor(Color.parseColor("#f13d1a"));
            }
            rightbtn.setVisibility(View.GONE);
        }

        String[] mTitles = null;

        if (productType == 1) {//现货
            String[] t = {getString(R.string.sold_on),
                    getString(R.string.sold_draft),

                    getString(R.string.sold_out)
            };
            mTitles = t;
        } else if (productType == 2) {//预售
            String[] t = {getString(R.string.sold_on),
                    getString(R.string.sold_draft),
                    getString(R.string.sold_audit),
                    getString(R.string.sold_out)
            };
            mTitles = t;
        }

        ArrayList<TabEntity> mTabEntities = new ArrayList<>();
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], 0, 0));
        }

        StoreInfo storeInfo = getStoreInfo();

        if (storeInfo != null && storeInfo.getStore() != null && storeInfo.getStore().isDc()) {
            vPreSales.setVisibility(View.GONE);
            isDc = true;
        } else {
            isDc = false;
        }
        lyTab.setTabData(mTabEntities);
        lyTab.setOnTabSelectListener(this);
        vp.setOffscreenPageLimit(pageCount);
        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentFragmentIndex = position;
                lyTab.setCurrentTab(currentFragmentIndex);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        vp.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                //    (0, "草稿"),
                //    (1, "已上架"),
                //    (2, "未上架"),
                //    (4, "审核中")
                if (position == 0) {
                    if (soldUpFragment == null) {
                        soldUpFragment = new SoldFragment();
                        soldUpFragment.isDc = isDc;
                        soldUpFragment.type = 1;

                        if (productType == 1) {//现货
                            soldUpFragment.saleType = 1;
                        } else if (productType == 2) {//预售
                            soldUpFragment.saleType = 2;
                        }

                    }
                    currentFragment = soldUpFragment;
                } else if (position == 1) {
                    if (soldDraftFragment == null) {
                        soldDraftFragment = new SoldFragment();
                        soldDraftFragment.isDc = isDc;
                        soldDraftFragment.type = 0;
                        if (productType == 1) {//现货
                            soldDraftFragment.saleType = 1;
                        } else if (productType == 2) {//预售
                            soldDraftFragment.saleType = 2;
                        }
                    }
                    currentFragment = soldDraftFragment;

                } else if (productType == 2 && position == 2) {
                    if (soldAuditFragment == null) {
                        soldAuditFragment = new SoldFragment();
                        soldAuditFragment.isDc = isDc;
                        soldAuditFragment.type = 4;
                        if (productType == 1) {//现货
                            soldAuditFragment.saleType = 1;
                        } else if (productType == 2) {//预售
                            soldAuditFragment.saleType = 2;
                        }
                    }
                    currentFragment = soldAuditFragment;

                } else {
                    if (soldDownFragment == null) {
                        soldDownFragment = new SoldFragment();
                        soldDownFragment.isDc = isDc;
                        soldDownFragment.type = 2;
                        if (productType == 1) {//现货
                            soldDownFragment.saleType = 1;
                        } else if (productType == 2) {//预售
                            soldDownFragment.saleType = 2;
                        }
                    }
                    currentFragment = soldDownFragment;

                }
                currentFragmentIndex = position;
                return currentFragment;
            }

            @Override
            public int getCount() {
                return pageCount;
            }
        });

        vp.setCurrentItem(currentFragmentIndex);

    }

    //当前选中的tab
    @Override
    public void onTabSelect(int position) {
        vp.setCurrentItem(position);
//        selectPage(position);
    }

    //再次点击当前选中的tab
    @Override
    public void onTabReselect(int position) {

    }

    public int getCurrentIndex(){
        return vp.getCurrentItem();
    }

    //根据tag寻找fragment
    public void initFragment() {
        soldUpFragment = (SoldFragment) fragmentManager.findFragmentByTag(Constant.TAG_SOLD_IN_FRAGMENT);
        soldDownFragment = (SoldFragment) fragmentManager.findFragmentByTag(Constant.TAG_SOLD_OUT_FRAGMENT);
        soldDraftFragment = (SoldFragment) fragmentManager.findFragmentByTag(Constant.TAG_SOLD_DRAFT_FRAGMENT);
        soldAuditFragment = (SoldFragment) fragmentManager.findFragmentByTag(Constant.TAG_SOLD_AUDIT_FRAGMENT);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.rl_cash_sales:
                if (BaseApplication.getInstance().getMerchant().isAuthNeedBind()) {
                    T.toast("暂无权限");
                }else {
//                addCashProduct();
                    addProduct();
                }
                break;
            case R.id.rl_pre_sales:
                if (BaseApplication.getInstance().getMerchant().isAuthNeedBind()) {
                    T.toast("暂无权限");
                }else {
//                addPreProduct();
                    addProduct();
                }
                break;
        }
    }

    private void addCashProduct() {
        Intent intent = new Intent(this, ProductAddActivity.class);
        //现售1
        if (productType == 1) {//现货
            intent.putExtra(Constant.TYPE, "1");
        } else if (productType == 2) {//预售
            intent.putExtra(Constant.TYPE, "2");
        }

        intent.putExtra("is_first", true);

        startActivityForResult(intent, 0x45);
    }
    private void addProduct() {
        Intent intent = new Intent(this, ProductAddCategoryActivity.class);
        //现售1
        if (productType == 1) {//现货
            intent.putExtra(Constant.TYPE, "1");
        } else if (productType == 2) {//预售
            intent.putExtra(Constant.TYPE, "2");
        }

        intent.putExtra("is_first", true);

        startActivityForResult(intent, 0x65);
    }

    private void addPreProduct() {
        Intent intent = new Intent(this, ProductAddActivity.class);
        //预售2
        intent.putExtra(Constant.TYPE, "2");
        intent.putExtra("is_first", true);
        startActivityForResult(intent, 0x45);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        //记录当前fragment的下标
        outState.putInt(Constant.KEY_HOME_STATE_INDEX, currentFragmentIndex);
        outState.putInt("productType", productType);
        super.onSaveInstanceState(outState);
    }


    public void refreshList() {
        if (soldUpFragment != null)
            soldUpFragment.refreshWithHeader();
        if (soldDownFragment != null)
            soldDownFragment.refreshWithHeader();

        if (soldDraftFragment != null)
            soldDraftFragment.refreshWithHeader();
        if (soldAuditFragment != null)
            soldAuditFragment.refreshWithHeader();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0x65 && resultCode == RESULT_OK) {
            refreshList();
        }
    }
}
